import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Table, DatePicker, Input, Card, Popconfirm } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryOccupySettleListParams, OccupySettle } from './services';
import { queryOccupySettleList } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import StationSelect from '@/components/StationSelect';
import dayjs from 'dayjs';
import OrgSelect from '@/components/OrgSelect';
import { Access } from '@@/exports';
import { AppUserStatus } from '@/pages/normal/normalList/services';
import DealRecordModal from '@/pages/normal/normalList/components/DealRecordModal';
import ShareStationModal, { ShareStationModalProps } from '@/pages/moneySettle/shareCount/shareStationModal';

const OccupySettlePage: React.FC<RoutePageProps> = (props) => {
  const [searchForm] = Form.useForm<QueryOccupySettleListParams>()
  const [dealRecordModalProps, setDealRecordModalProps] = useState<ShareStationModalProps>({
    open: false
  })
  const [searchParams, setSearchParams] = useState<QueryOccupySettleListParams>({
    pageNum: 1, pageSize: 10,
    beginDay: dayjs().subtract(31, 'days').format('YYYYMMDD'),
    endDay: dayjs().format('YYYYMMDD'),
  })
  const list = useRequest(() => queryOccupySettleList(searchParams), {
    refreshDeps: [searchParams],
  })

  const openDealRecordModal = (record: OccupySettle) => {
    setDealRecordModalProps({
      open: true, orgId: record.orgId
    })
  }

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      orgId: formValues.org ? formValues.org?.id : undefined,
      beginDay: formValues.timeRange[0]?.format('YYYYMMDD'),
      endDay: formValues.timeRange[1]?.format('YYYYMMDD'),
      pageNum: 1,
    })
  }

  const onDealRecordModalCancel = () => {
    setDealRecordModalProps({open: false})
  }

  const columns: ColumnsType<OccupySettle> = [
    {
      title: '名称',
      dataIndex: 'orgName',
      width: 120,
    },
    {
      title: '数量',
      dataIndex: 'num',
      width: 140,
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 200,
      fixed: 'right',
      render: (id: number, record) => {
        return <Space>
          <a onClick={() => openDealRecordModal(record)}>查看明细</a>

        </Space>
      }
    }
  ]

  useEffect(() => {
    if (props.params.sKey) {
      const _paramsStr = sessionStorage.getItem(props.params.sKey.split('___')[0])
      if (_paramsStr) {
        const _params = JSON.parse(_paramsStr)
        let __params: any = undefined
        if (props.params.sKey.startsWith('_searchParams_settleDetail')) {
          __params = {
            station: [{
              id: _params.stationId,
              name: _params.stationName,
            }],
            orderCode: _params.settleId,
            timeRange: [dayjs(_params.beginDay), dayjs(_params.endDay)],
          }
        }
        if (__params) {
          searchForm.setFieldsValue(__params)
          onFinish(__params)
        }
      }
    }
  }, [])

  return (
    <div className='container'>
      <Card>
        <div className="search-card">
          <Form name='searchOccupySettleForm' form={searchForm} onFinish={onFinish} initialValues={{
            timeRange: [dayjs().subtract(31, 'days'), dayjs()]
          }}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='经理人' name='org'>
                  <OrgSelect allowClear inline />
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label='结算时间' name='timeRange'>
                  <DatePicker.RangePicker allowClear={false} style={{width: '100%'}} disabledDate={current => current.isAfter(dayjs(), 'day')} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </Card>
      <Card title='共享上线数量统计'>
        <Table<OccupySettle>
          rowKey='id'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </Card>
      <ShareStationModal
        {...dealRecordModalProps}
        onCancel={onDealRecordModalCancel}
      />
    </div>
  );
};

export default OccupySettlePage;
